package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

public class BootStrap {
    /** 定义监听端口号*/
    private  int port=8080;

    //项目路径
    private String webappsPath="";

    private Map<String,Map<String,Map<String,HttpServlet>>> hostMap = new HashMap<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
    /**minicat启动需要初始化展开得一些操作*/
    public  void  start() throws Exception {
        //加载解析相关的配置
        loadServerXml();
        //定义一个线程池

        int corePoolSize=10;
        int maximumPoolSize=50;
        long keepAliveTime=100L;
        TimeUnit unit=TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(50) ;
        ThreadFactory threadFactory=Executors.defaultThreadFactory();
        RejectedExecutionHandler handler =new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.printf("========>>> minicat start on port:" +port);

        //完成1.0版本 （浏览器请求 localhost：8080,返回固定得字符串回到页面）
      /*  while (true){
            Socket socket = serverSocket.accept();
            //有了socket 接收到请求，
            OutputStream outputStream = socket.getOutputStream();
            String responseText= HttpProtocolUtil.getHttpHeader200("hello minicat".getBytes().length)+"hello minicat";
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成miniCat2.0
         * 需求,封装request和response对象,返回html静态资源文件
         */

       /* while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            response.outputHtml(request.getUrl());
            socket.close();
        }*/

        /***
         * 3.0版本.可以请求动态资源
         */
      /*  while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            HttpServlet httpServlet = servletMap.get(request.getUrl());
            if(httpServlet==null){

                response.outputHtml(request.getUrl());
            }else {
                httpServlet.service(request,response);
            }
            socket.close();
        }*/

        /**
         * 多线程改造
         */
       /* while(true){
            Socket socket = serverSocket.accept();
            RequestProcessorr requestProcessorr = new RequestProcessorr(socket,servletMap);
            requestProcessorr.start();
        }*/

        /**
         * 线程池改造多线程
         */
      /*  while(true){
            Socket socket = serverSocket.accept();
            RequestProcessorr requestProcessorr = new RequestProcessorr(socket,servletMap);
            //requestProcessorr.start();
            threadPoolExecutor.execute(requestProcessorr);
        }*/

        /***
         * 多项目部署
         */
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessorNew requestProcessorr = new RequestProcessorNew(socket,hostMap,webappsPath);
            threadPoolExecutor.execute(requestProcessorr);
        }

    }
    private Map<String,HttpServlet> servletMap=new HashMap<String,HttpServlet>();
    /**
     * 加载解析web.xml 初始化servlet
     */
  /*  private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(resourceAsStream);
            Element rootElement = read.getRootElement();
            List<Element> servletNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < servletNodes.size(); i++) {
                Element element = servletNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element)element.selectSingleNode("servlet-name");
                String servletname=servletnameElement.getStringValue();
                //<servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element)element.selectSingleNode("servlet-class");
                String servletclass=servletclassElement.getStringValue();

                //根据servler-name的值找到uel-pattern
                Element servletMapping = (Element)rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletname + "']");
                //  /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                    servletMap.put(urlPattern, (HttpServlet) Class.forName(servletclass).newInstance());

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }*/

    /**
     * Minicat得启动入口
     */

    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();
        try {
            bootStrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 解析server.xml
     */
    public void loadServerXml() throws Exception {
        InputStream resourceAsStream = BootStrap.class.getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        Element server = (Element) rootElement.selectSingleNode("//Server");
        List<Element> list = server.selectNodes("//Service");
        for (Element element : list) {
            Element connect = (Element) element.selectSingleNode("//Connect");
            //端口号
            port = Integer.parseInt(connect.attributeValue("port"));

            Element engine = (Element) element.selectSingleNode("//Engine");

            List<Element> hostElement = engine.selectNodes("//Host");

            for (Element host : hostElement) {
                //ip 域名
                String ip = host.attributeValue("name");
                //项目地址/路径
                String appBase = host.attributeValue("appBase");
                webappsPath = appBase;

                Map<String,  Map<String, HttpServlet>> contextMap = new HashMap<>();

                File file = new File(webappsPath);
                //判断是否存在
                if (file.exists() && !file.isFile()) {
                    File[] files = file.listFiles();
                    //便利项目
                    for (File app : files) {
                        Map<String, HttpServlet> wapperMap = new HashMap<>();
                        String path = app.getPath();
                        String name = path.substring(path.lastIndexOf("\\") + 1);
                        InputStream stream = new FileInputStream(path + "\\" + "web.xml");
                        //InputStream stream = BootStrap.class.getClassLoader().getResourceAsStream(path + "\\" + "web.xml");
                        SAXReader reader = new SAXReader();
                        Document read = reader.read(stream);
                        Element readRootElement = read.getRootElement();
                        List<Element> elementList = readRootElement.selectNodes("//servlet");
                        for (Element element1 : elementList) {
                            //<servlet-name>lagou</servlet-name>
                            String servletName = element1.selectSingleNode("//servlet-name").getStringValue();

                            //<servlet-class>server.LagouServlet</servlet-class>
                            String servletClass = element1.selectSingleNode("//servlet-class").getStringValue();

                            //<servlet-mapping> 下的  <servlet-name>lagou</servlet-name>
                            //Element servletMapping = (Element) readRootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name=" + servletName + "]");
                            Element servletMapping = (Element) readRootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");

                            // <url-pattern>/lagou</url-pattern>
                            String urlPattern = servletMapping.selectSingleNode("//url-pattern").getStringValue();

                            // 自定义类加载器，来加载 webapps 目录下的 class
                            DZYClassLoader dzyClassLoader = new DZYClassLoader(path);
                            Class<?> aClass = dzyClassLoader.findClass(servletClass);
                            wapperMap.put(urlPattern, (HttpServlet) aClass.getDeclaredConstructor().newInstance());
                        }
                        contextMap.put(name ,wapperMap);
                    }

                }
                hostMap.put(ip, contextMap);
            }



        }
    }



}
